/*
  * @date 2020-02-03
  * @author wolfMan
  * @description {}
*/

import request from '@/utils/request'

export default {
  props: {
    // 显示dialog
    show: {
      type: Boolean,
      default: false
    },
    api: {
      type: String,
      default: 'admin/promotion/coupons/all'
    },
    // 最大可选个数
    limit: {
      type: Number,
      default: 10
    },
    // 默认数据
    defaultData: {
      type: Array,
      default: () => ([])
    }
  },
  data() {
    return {
      /** 加载状态 */
      loading: false,
      /** 商品列表 */
      couponData: [],
      /** 已选列表 */
      selectedList: [],
      dialogVisible: this.show
    }
  },
  watch: {
    show(newVal) {
      this.dialogVisible = newVal
      if (this.couponData.length === 0 && newVal === true) {
        this.GET_CouponList()
      }
    },
    dialogVisible(newVal) {
      newVal === false && this.$emit('close')
    },
    'defaultData': 'defaultDataChanged'
  },
  computed: {
    /** 计算已选择个数 */
    selectedNum() {
      return this.selectedList.filter(item => item).length
    }
  },
  methods: {
    /** 确认 */
    handleConfirm() {
      if (!this.selectedList.length) {
        this.$message.error('请选择优惠券')
        return
      }
      let _data = [];
      _data = this.selectedList.map(item => {
        return {
          id: item.coupon_id,
          title: item.title
        }
      });
      this.$emit('confirm', _data)
      this.$emit('close')
      this.$refs.couponTable.clearSelection()
      this.selectedList = []
    },
    /** 当默认数据发生改变 */
    defaultDataChanged(newVal) {
      this.selectedList = []
      if (newVal && newVal.length > 0) {
        this.$nextTick(() => {
          this.couponData.forEach(row => {
            if(newVal.indexOf(row.coupon_id) >= 0){
              this.$refs.couponTable.toggleRowSelection(row, true);
            }
          })
        })
      }
    },
    /** 选择优惠券 */
    handleCouponSelect (_row) {
      this.selectedList = _row;
    },
    /** 获取优惠券列表 */
    async GET_CouponList(clean = false) {
      this.loading = true
      await request({
        url: this.api,
        method: 'get',
        loading: false
      }).then(response => {
        this.loading = false
        const data = response.data
        // 如果clean为true，先清空couponData
        !!clean && (this.couponData = [])
        this.$nextTick(() => {
          this.couponData = data
        });
      })
    }
  }
}
